<template>
  <div>
    <div class="org-container">
      <div class="org-content">
        <div class="org-header">
          <span>产品基础信息管理</span>
          <div>
            <el-button type="primary" size="mini" plain @click="addProduction">新增产品</el-button>
            <el-button type="primary" size="mini" plain @click="importVisible = true; importType=[]">
              模板下载
            </el-button>
            <el-button type="primary" size="mini" plain @click="exportVisible = true; importType=[]">
              导入产品
            </el-button>
          </div>
        </div>
        <div class="production-operator">
          <div class="itemTitle">
            <span class="org-label">产品类型</span>
            <el-select v-model="selectedType" size="mini" style="width: 156px;">
              <el-option
                label="全部"
                value="">
              </el-option>
              <el-option
                v-for="item in productionTypes"
                :key="item.entry"
                :label="item.entry"
                :value="item.entry"
              >
              </el-option>
            </el-select>
          </div>
          <div>
            <span class="org-label">行业/品类/型号</span>
            <el-cascader
              size="mini"
              class="production-cascader"
              :options="productionTree"
              v-model="selectedProduction"
              :props="productionTreeProps"
              change-on-select
              clearable
            ></el-cascader>
          </div>
          <div class="production-price org-label">
            <span>
              价格范围
            </span>
            <el-input size="mini" type="number" v-model="minPrice" placeholder="最小价格"></el-input>
            -
            <el-input size="mini" type="number" v-model="maxPrice" placeholder="最大价格"></el-input>
          </div>
          <div>
            <el-button size="mini" type="primary" @click="currentPage = 1;onSearch()">搜索</el-button>
          </div>
          <div class="org-label org-right">共{{total}}条数据</div>
        </div>
        <div>
          <el-table
            :data="tableData"
            style="width: 100%">
            <el-table-column
              prop="productMainImage"
              label="产品主图">
              <template slot-scope="scope">
                <div style="margin-left: 10px;width: 100px; height: 100px;">
                  <img :src="getImageUrl(scope.row.productMainImage)" alt="产品主图" class="product-image">
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="productName"
              label="产品名称">
            </el-table-column>
            <el-table-column
              prop="categoryName"
              label="所属品类">
            </el-table-column>
            <el-table-column
              prop="productCode"
              label="型号">
            </el-table-column>
            <el-table-column
              prop="productType"
              label="产品类型">
            </el-table-column>
            <el-table-column
              prop="skuNum"
              label="SKU数量">
            </el-table-column>
            <el-table-column
              prop="guidePrice"
              label="产品价格">
            </el-table-column>
            <el-table-column label="操作" width="200">
              <template slot-scope="scope">
                <el-button type="text" @click="editProduction(scope.row)">查看</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            style="float: right"
            layout="prev, pager, next"
            :total="total"
            :current-page="currentPage"
            @current-change="pageChange">
          </el-pagination>
        </div>
      </div>
    </div>
    <el-dialog
      title="录入新产品"
      :visible.sync="addProductionPanelVisible"
      :close-on-click-modal="false"
      width="40%">
      <el-form ref="form" :model="form" label-width="120px">
        <el-form-item label="产品名称">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="行业/品类">
          <el-cascader
            class="add-production-cascader"
            :options="categoryTree"
            v-model="form.createdCategory"
            :props="categoryProps"
            change-on-select
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="产品型号">
          <el-input v-model="form.productCode"></el-input>
        </el-form-item>
        <el-form-item>
          <div class="dialog-footer">
            <el-button type="primary" @click="createProduction">立即创建</el-button>
            <el-button @click="cancelCreation">取 消</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog
      title="模板下载"
      :visible.sync="importVisible"
      :close-on-click-modal="false"
      width="40%">
        <div style="margin-bottom: 10px;">请选择行业</div>
        <el-cascader
          class="add-production-cascader"
          :options="categoryTree"
          v-model="importType"
          :props="categoryImportProps"
          clearable
        ></el-cascader>
      <div style="margin-top: 10px;"><a :href="downloadUrl" class="org-link" v-if="importType.length !== 0" download>模板下载</a></div>
    </el-dialog>
    <el-dialog
      title="导入产品"
      :visible.sync="exportVisible"
      :close-on-click-modal="false"
      width="40%">
        <div style="margin-bottom: 10px;">请选择行业</div>
        <el-cascader
          class="add-production-cascader"
          :options="categoryTree"
          v-model="importType"
          :props="categoryProps"
          clearable
        ></el-cascader>
      <div style="margin-top: 10px;" v-if="importType.length !== 0">
        <el-upload
          class="upload-demo"
          :action="uploadUrl"
          :data="uploadConfig"
          :headers="headers"
          name="file"
          :show-file-list="false"
          :multiple="false"
          :file-list="fileList"
          :on-success="onUpload">
          <el-button size="small" type="text">导入</el-button>
        </el-upload>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name: "production-management",
    data() {
      return ({
        selectedType: '',
        productionTypes: [],
        productionTree: [],
        selectedProduction: [],
        productionTreeProps: {
          children: 'children',
          label: 'name',
          value: 'id'
        },
        categoryProps: {
          children: 'children',
          label: 'categoryName',
          value: 'id'
        },
        minPrice: undefined,
        maxPrice: undefined,
        currentPage: 1,
        total: 1,
        productionList: [],
        tableData: [],
        addProductionPanelVisible: false,
        createdCategory: [],
        categoryTree: [],
        form: {},
        exportVisible: false,
        importVisible: false,
        importType: [],
        fileList: [],
        categoryImportProps: {
          children: 'children',
          label: 'categoryName',
          value: 'categoryName'
        },
        uploadUrl: '/front/excelUpload',
      })
    },
    computed: {
      downloadUrl: function() {
        const str = _.last(this.importType)
        return `/file/download?fileName=产品模板（产品档案管理）_${str}.xlsx`
      },
      uploadConfig: function() {
        return ({
          method:'File_ImportProduct',
          categoryId: _.last(this.importType),
          creator: this.$store.state.user.id,
        })
      },
      headers: function() {
        let token = sessionStorage.getItem("tokenName")
        return ({
          dipsToken: token,
        })
      }
    },
    mounted() {
      this.getProductionTypes()
      this.getProductionCategory()
      this.getCategoryForEditor()
      this.onSearch()
    },
    methods: {
      getProductionTypes() {
        this.$http.post(this.GLOBAL.host, {
          "method":"Product_GetType",
          "query":{}
        }).then(res => {
          this.productionTypes = res.data.data
        })
      },
      getProductionCategory() {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        this.$http.post(this.GLOBAL.host, {
          "method":"Category_ProductTree",
          "query":{}
        }).then(res => {
          loading.close()
          this.productionTree = res.data.data
        })
      },
      getCategoryForEditor() {
        this.$http.post(this.GLOBAL.host, {
          "method":"Category_CategoryTree",
          "query":{}
        }).then(res => {
          this.categoryTree = res.data.data
          this.updateData({
            categoryTree: res.data.data,
          })
        })
      },
      onSearch(lastQuery) {
        this.lastQuery = lastQuery || {
          pageNo: this.currentPage || 1,
          pageSize: 10,
          minPrice: this.minPrice,
          maxPrice: this.maxPrice,
          productType: this.selectedType,
          level: this.selectedProduction.length,
          id: _.last(this.selectedProduction),
        };
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        this.$http.post(this.GLOBAL.host, {
          method:"Product_PageList",
          query: _.omitBy(this.lastQuery, (value) => {
            return value === ''
          }),
        }
        ).then(res => {
          loading.close()
          this.tableData = res.data.data.list
          this.total = res.data.data.total
        })
      },
      pageChange(pageNum) {
        this.currentPage = pageNum;
        this.onSearch()
      },
      getPathByKey(value, key, arr) {
        let temppath = [];
        try {
          function getNodePath(node){
            temppath.push(node);
            //找到符合条件的节点，通过throw终止掉递归
            if (node[key] === value) {
              throw ("GOT IT!");
            }
            if (node.children && node.children.length > 0) {
              for (var i = 0; i < node.children.length; i++) {
                getNodePath(node.children[i]);
              }

              //当前节点的子节点遍历完依旧没找到，则删除路径中的该节点
              temppath.pop();
            }
            else {

              //找到叶子节点时，删除路径当中的该叶子节点
              temppath.pop();
            }
          }
          for (let i = 0; i < arr.length; i++) {
            getNodePath(arr[i]);
          }
        } catch (e) {
          return temppath;
        }
      },
      addProduction() {
        this.form = {}
        this.addProductionPanelVisible = true
      },
      cancelCreation() {
        this.addProductionPanelVisible = false
        this.$refs.form.resetFields()
      },
      createProduction() {
        const categoryId = _.last(this.form.createdCategory)
        if (categoryId) {
          this.$refs.form.resetFields()
          this.$router.push({
            path: `/full/organization/production-management/${categoryId}`,
            query: ({
              productCode: this.form.productCode,
              name: this.form.name,
            })
          })
        } else {
          this.$message({
            message: '请选择品类',
            type: 'error'
          });
        }
      },
      editProduction(data) {
        this.$router.push({
          path: `/full/organization/production-management/${data.categoryId}`,
          query: ({
            productId: data.productId,
          })
        })
      },
      updateData(data) {
        this.$store.commit('updateProductionData', data)
      },
      getProductionTypeById(id) {
        const productionTypes = this.productionTypes
        return _.get(_.find(productionTypes, item => item.id == id), 'entry')
      },
      getImageUrl(url) {
        if (url) {
          return `http://${url}`
        }
        return undefined
      },
      onUpload(res) {
        if (res.code == 200) {
          this.$message({
            message: res.data || '上传成功',
            type: 'success',
            showClose: true,
            duration: 0,
          });
        } else {
          this.$message({
            message: res.data || '上传失败',
            type: 'error',
            showClose: true,
            duration: 0,
          });
        }
      },
    }
  }
</script>

<style lang="less">
  .production-operator {
    display: flex;
    align-items: center;
    > div {
      margin-right: 15px;
    }
    margin-bottom: 10px;
  }
  .production-filter {
    width: 200px;
  }
  .production-item {
    display: flex;
    margin: 10px 0;
    > div {
      width: 400px;
    }
    > span {
      margin-right: 20px;
    }
  }
  .production-price {
    display: flex;
    align-items: center;
    > div {
      width: 100px;
      margin: 0 10px;
    }
  }
  .product-image {
    width: 100%;
    height: 100%;
  }
  .upload-demo {
    .el-upload__input {
      display: none;
    }
  }
</style>
